<template>
  <basic-dialog
    :visible="visible"
    min-width="620px"
    isShowBasicFooter
    :isShowInnerLoading="loading"
    @close="visible=false"
    :title="`当前${statusList[1].label}`"
    @submit="submit">
    <div class="padding-20">
      <q-form greedy ref="form">
        <div>
          <div class="margin-b-20 font-16" style="color: #333">
            {{ statusList[1].label }}时长: {{ downTime }}
          </div>
          <div class="flex justify-between">
            <div>
              <yz-input style="width: 260px" input-type="select" v-model="stopType" :options="stopTypeList" :title="`${statusList[1].label}类型`" :rules="[0]"></yz-input>
            </div>
            <div>
              <yz-input style="width: 260px" input-type="select" v-model="stopCause" :title="`${statusList[1].label}原因`" :options="stopCauseList" :rules="[0]"></yz-input>
            </div>
          </div>
          <div class="flex justify-between">
            <div>
              <select-tree label="所在部门" :sel-tree="selDepartment" ref="selectTree"
                           :tree-list="departments" node-key="id" style="width: 260px;padding-left: 7px"
                           @treeChange="_changeTreeNode" />
            </div>
            <div>
              <fuzzy-search
                style="width: 260px;padding-left: 7px"
                v-model.trim="operatorId"
                :fuzzyParams="fuzzyParams"
                fuzzyNumber="keyword"
                :isShowValue="false"
                :fuzzyObj="['name', 'id']"
                showAllOption
                :title="`${statusList[1].label}人员`"
                :fuzzyFunc="getUserFilter"
                @onSelect="getCurrentUserList"
              ></fuzzy-search>
            </div>
          </div>
          <div>
            <yz-input style="padding-left: 7px" input-type="textarea" v-model="remark" :maxlength="100" title="备注信息"></yz-input>
          </div>
        </div>
      </q-form>
    </div>
  </basic-dialog>
</template>

<script>
import { getCauseItemNew, getCauseTypeList } from '../../../boot/system/reason'
import SelectTree from 'src/components/select-tree'
import userManageApi, { getUserFilter } from '../../../boot/system/user-manage'
import _ from 'lodash'
import { secondToString } from '../../../assets/js/util'
import { setCurrentStopCause } from '../../../boot/status-monitor/machine'
import { mapGetters } from 'vuex'

export default {
  name: 'current-shutdown-dialog',
  components: {
    SelectTree
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      visible: false,
      loading: false,
      stopType: '',
      stopCause: '',
      stopTypeList: [], // 停机原因类型
      stopTypeDetail: {},
      selDepartment: {}, // 所在位置
      departments: [], // 部门列表
      stopCauseList: [],
      userList: [],
      userDetail: {},
      operatorId: null,
      data: {},
      remark: '',
      oldSecond: 0,
      timer: null,
      getUserFilter: getUserFilter,
      fuzzyParams: {
        pageNum: 1,
        pageSize: 100000,
        departmentId: '',
        searchBy: 'name'
      }
    }
  },
  created () {
    this.getStopcauseList()
    this.getDepartmentsTree()
  },
  computed: {
    ...mapGetters(['statusList']),
    downTime () {
      return secondToString(this.oldSecond)
    }
  },
  watch: {
    stopType: {
      handler (val) {
        if (val) {
          this.getCauseItem(val, true)
        }
      }
    },
    visible (val) {
      if (val) {
        this.selDepartment.id = this.departments[0].id
        this.selDepartment.level = this.departments[0].level
        this.selDepartment.label = this.departments[0].label
        this.fuzzyParams.departmentId = this.departments[0].id
        this.operatorId = null
        this.remark = ''
        if (this.stopTypeList.length > 0) {
          this.stopType = this.stopTypeList[0].value
        }
        this.$nextTick(() => {
          this.$refs.selectTree.setValue(this.selDepartment)
        })
      } else {
        clearInterval(this.timer)
      }
    }
  },
  methods: {
    showDialog (oldSecond) {
      clearInterval(this.timer)
      // 当前停机的秒数
      this.oldSecond = oldSecond + 1
      this.visible = true
      // 动态显示停机时长
      this.timer = setInterval(() => {
        this.oldSecond++
      }, 1000)
    },
    hideDialog () {
      this.visible = false
    },
    // 获取原因类型列表
    getStopcauseList () {
      getCauseTypeList(3, this.isFilter).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(o => {
            // 让步原因类型map（为取让步名）
            this.stopTypeDetail[o.id] = o.label
            this.stopTypeList.push({
              value: o.id,
              label: o.label
            })
          })
          if (res.data && res.data.length > 0) {
            this.stopType = res.data[0].id
          }
        }
      })
    },
    // 根据停机原因类型代码查询停机原因
    getCauseItem (typeId, isChange) {
      const params = {
        id: typeId,
        showDisable: false
      }
      this.stopCauseList = []
      this.stopCauseDetail = {}
      this.stopCause = ''
      getCauseItemNew(params).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(o => {
            this.stopCauseDetail[o.id] = o.label
            this.stopCauseList.push({
              value: o.id,
              label: o.label
            })
          })
          if (res.data && res.data.length > 0) {
            this.stopCause = res.data[0].id
          }
        } else {
          this.stopCause = null
        }
      })
    },
    _changeTreeNode (val) {
      this.operatorId = ''
      if (val.id && val.label) {
        this.selDepartment.id = val.id
        this.selDepartment.level = val.level
        this.selDepartment.label = val.label
        this.fuzzyParams.departmentId = val.id
        // this.listUsers(true)
      }
    },
    getCurrentUserList (val, option) {
      this.userList = option
    },
    /**
     * 列举用户
     */
    listUsers (isChange) {
      this.userList = []
      const queryParams = {
        departmentId: this.selDepartment.id
      }
      if (!this.data.operatorId) {
        this.userList[0] = {
          value: null,
          label: '--'
        }
      } else {
        if (!this.isReports && !isChange) {
          this.$nextTick(() => {
            this.operatorId = this.data.operatorId
          })
        }
      }
      userManageApi.listUsers(1, 100000, queryParams).then(res => {
        res.list.forEach(o => {
          // 让步原因map（为取让步名）
          this.userDetail[o.id] = o.name
          this.userList.push({
            value: o.id,
            label: o.name
          })
        })
        if (isChange) {
          this.$nextTick(() => {
            this.operatorId = _.isEmpty(this.userList) ? '-' : this.userList[0].value
          })
        }
      })
    },
    /**
     * 获取部门 tree
     */
    getDepartmentsTree () {
      userManageApi.getDepartmentsTree().then(res => {
        let departments = res.filter(item => item.type !== 'cc' && item.type !== 'cg')
        this.departments = departments
      })
    },
    reorganize (node) {
      if (node.id === this.data.deptId) {
        this.selDepartment.id = node.id
        this.selDepartment.level = node.level
        this.selDepartment.label = node.label
      }

      if (node.children instanceof Array && !this.selDepartment.id) {
        node.children.forEach(this.reorganize)
      }
    },
    getDuration (second) {
      if (second > 0 && second < 60) {
        let seconds = second
        return {
          duration: seconds,
          unit: '秒'
        }
      } else if (second >= 60 && second < 3600) {
        let minutes = Math.floor(parseInt(second) / 60)
        return {
          duration: minutes,
          unit: '分'
        }
      } else if (second >= 3600 && second < (3600 * 24)) {
        let hours = Math.floor(parseInt(second) / 3600)
        return {
          duration: hours,
          unit: '时'
        }
      } else {
        let days = Math.floor(parseInt(second) / (3600 * 24))
        return {
          duration: days,
          unit: '天'
        }
      }
    },
    submit () {
      this.$refs.form.validate().then(success => {
        if (success) {
          const data = {
            causeId: this.stopCause,
            cause: this.stopCauseList.find(item => item.value === this.stopCause) ? this.stopCauseList.find(item => item.value === this.stopCause).label : '',
            deptId: this.selDepartment.id,
            operatorId: this.operatorId,
            operatorName: this.operatorId ? (this.userList.find(item => item.value === this.operatorId) ? this.userList.find(item => item.value === this.operatorId).label : '') : '',
            remark: this.remark,
            typeId: this.stopType,
            type: this.stopTypeList.find(item => item.value === this.stopType) ? this.stopTypeList.find(item => item.value === this.stopType).label : ''
          }
          this.loading = true
          setCurrentStopCause(this.id, data).then(res => {
            this.visible = false
            this.$emit('setSuccess')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
/deep/ .form-name {
  font-size 16px
  color #333
}
/deep/ .input-select{
  margin-bottom 0!important;
}
/deep/ .name{
  font-size: 16px;
}
</style>
